# 计科1915班 0306224505 屠玉宝

import requests
from lxml import etree


class Picture:
    def __init__(self):
        self.url = 'https://www.nipic.com/topic/show_27313_1.html'
        self.headers = {
            "User-Agent": "AttributeError: 'NoneType' object has no attribute 'xpath'"
        }
        self.img_list = []

    def get_html(self, url):
        html = requests.get(url=url, headers=self.headers)
        return html

    def parse(self, html, num=10):
        tree = etree.HTML(html)
        imgs = tree.xpath('//li//img/@src')
        for img in imgs:
            self.img_list.append("https:" + img)
            if self.img_list.index("https:" + img) > num - 2:
                break

    def save(self):
        for url in self.img_list:
            image = self.get_html(url)
            with open(f'./images/{url[-10:]}', "wb") as f:
                f.write(image.content)
            print(url[-10:]+"  success")

    def run(self, num):
        html = self.get_html(self.url).text
        self.parse(html, num)
        self.save()


if __name__ == '__main__':
    num = int(input("请输入爬取个数："))
    p = Picture()
    p.run(num)
